package cn.glenn._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 日志功能切面类
 */

@Aspect
@Component
public class LogAspect {

    @Pointcut(value = "execution(public int cn.glenn._07springaop.aop.CalculatorImpl.*(..))")
    public void doTime(){}
    /**
     * Before注解：
     * 1.前置通知，调用目标方法之前需要执行的方法；
     *
     */
//    @Before(value = "execution(public int cn.glenn._07springaop.aop.CalculatorImpl.*(..))")
    @Before(value = "within(cn.glenn._07springaop.aop.CalculatorImpl)")
//    @Before(value = "bean(calculatorImpl)")
    public void beforeMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();//从方法签名中获取方法名称；
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("前置通知："+name+"方法开始，参数为："+args);
    }

    @After(value = "within(cn.glenn._07springaop.aop.CalculatorImpl)")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("后置通知："+name+"方法结束");
    }

    /**
     * 返回通知：
     * 目标方法正常结束后执行
     * 有权限获取到目标方法的返回值
     */

    @AfterReturning(value = "doTime()",returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("返回通知："+name+"方法执行结束，结果为："+result);
    }

    /**
     * 异常通知
     * 目标方法排除异常时执行
     * 异常通知有权限获取异常对象
     */
    @AfterThrowing(value = "doTime()",throwing = "e")
    public void afterThrowingMethod(JoinPoint joinPoint,Throwable e) {
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"抛出异常"+e.getMessage());

    }
    /**
     * 环绕通知
     * 在目标方法被调用的各个阶段植入增强逻辑
     * 等价于Before+After+AfterReturning+AfterThrowing
     * 通常使用try....catch....finally....结构
     */
    @Around(value = "doTime()")
    public Object aroundMethod(ProceedingJoinPoint pjp){
        Object result = null;
        try {
        //1,前置通知
            System.out.println("环绕通知-前置通知");
        //2,目标方法
            result = pjp.proceed();
        //3.返回通知
            System.out.println("环绕通知-返回通知");
        }catch (Throwable e) {
            //4.异常通知
            System.out.println("环绕通知-异常通知"+e.getMessage());
        }finally {
            //5.后置通知
            System.out.println("环绕通知-后置通知");
        }
        return result;
    }
}

